package com.gao.weblog.common.domain.mapper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gao.weblog.common.domain.dos.ArticleCategoryRelDO;
import com.gao.weblog.common.domain.dos.CategoryDO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface ArticleCategoryRelMapper extends BaseMapper<ArticleCategoryRelDO> {
    default int deleteByArticleId(Long articleId) {

        return delete(Wrappers.<ArticleCategoryRelDO>lambdaQuery()
                .eq(ArticleCategoryRelDO::getArticleId, articleId));
    }

    default Long selectByArticleId(Long articleId){
        LambdaQueryWrapper<ArticleCategoryRelDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleCategoryRelDO::getArticleId, articleId);
        return selectOne(wrapper).getCategoryId();
    }

    default List<ArticleCategoryRelDO> selectByArticleIds(List<Long> articleIds){
        return selectList(Wrappers.<ArticleCategoryRelDO>lambdaQuery()
                .in(ArticleCategoryRelDO::getArticleId, articleIds));
    }

    default List<ArticleCategoryRelDO> selectByCategoryId(Long categoryId){
        List<ArticleCategoryRelDO> articleCategoryRelDOS = selectList(Wrappers.<ArticleCategoryRelDO>lambdaQuery()
                .eq(ArticleCategoryRelDO::getCategoryId, categoryId));
        return articleCategoryRelDOS;
    }

    @Select("select c.*" +
            "from weblog.t_category c" +
            "join weblog.t_article_category_rel rel on rel.category_id = c.id" +
            "where rel.article_id = #{articleId}" +
            "limit 1")
    CategoryDO selectCategoryByArticleId(@Param("articleId") Long articleId);

    default int updateByArticleId(ArticleCategoryRelDO articleCategoryRelDO){
        LambdaQueryWrapper<ArticleCategoryRelDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ArticleCategoryRelDO::getArticleId, articleCategoryRelDO.getArticleId());
        return update(articleCategoryRelDO, wrapper);
    }
}
